package org.rency.crawler.fetch.service.policy.impl;

import java.time.LocalDateTime;
import javax.annotation.Resource;
import org.rency.common.utils.tool.LocalDateUtils;
import org.rency.crawler.domain.FetchHost;
import org.rency.crawler.fetch.helper.FetchCarrier;
import org.rency.crawler.fetch.repository.HostQueueRepository;
import org.rency.crawler.fetch.service.policy.PolicyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 描述: 目标服务器访问间隔校验<br>
 * 最近修改时间:2017/11/22 18:46<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/11/22 18:46
 */
@Service("intervalPolicyService")
public class IntervalPolicyServiceImpl implements PolicyService {

  private static final Logger logger = LoggerFactory.getLogger(IntervalPolicyServiceImpl.class);

  @Resource
  private HostQueueRepository       hostQueueRepository;

  @Override
  public String getPolicyName() {
    return "访问间隔";
  }

  @Override
  public boolean accept(FetchCarrier carrier) {
    FetchHost fetchHost = hostQueueRepository.get(carrier.getRequest().getFetchHost());

    //如果间隔时间小于等于0,或域名为空,或最近抓取时间为空,则无需交验
    if(fetchHost == null || fetchHost.getFetchIntervalTime() <= 0 || fetchHost.getLastedFetchTime() == null){
      logger.debug("策略校验{}-无需校验:{}.",this.getPolicyName(),carrier.getRequest().getFetchUri());
      return true;
    }

    long diff = LocalDateUtils.getDiffSeconds(fetchHost.getLastedFetchTime(),LocalDateTime.now());
    if( diff >= fetchHost.getFetchIntervalTime()){
      return true;
    }
    logger.warn("策略校验[{}]未通过,域名:{},最近访问:{},间隔时间:{}秒,距离最近访问间隔{}秒",this.getPolicyName(),fetchHost.getHostName(),LocalDateUtils.formatDateTime(fetchHost.getLastedFetchTime()),fetchHost.getFetchIntervalTime(),diff);
    return false;
  }

  @Override
  public boolean retrySupport() {
    return true;
  }
}
